from django.shortcuts import render, HttpResponse, redirect
# redirect快捷跳转
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

from django.contrib.auth.hashers import make_password
# Create your views here.
# 这引入的是各种视图，包括登录、注册、找回密码,修改密码
from .forms import LoginFrom, RegisterForm, ForgetPwdForm, ModifyPwdForm
# 发送邮件时需要使用
from .models import EmailVerifyRecord, UserProfile
# 验证用户是否登录，登录就可以访问，如果没有登录就跳转到指定的页面，这里设置跳转到登录页
from django.contrib.auth.decorators import login_required
# 引入发送邮件的方法，在新用户注册时使用
from utils.email_send import send_register_email


# 实现邮箱登录功能
class MyBackend(ModelBackend):
    """邮箱登录注册"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):  # 加密明文密码
                return user
        except Exception as e:
            return None


def active_user(request, active_code):
    """修改用户状态，比对链接验证码"""
    all_records = EmailVerifyRecord.objects.filter(code=active_code)

    # 如果有，就通过循环的方式获取其中的数据
    if all_records:
        for record in all_records:
            email = record.email
            # 根据邮箱地址获取一下用户
            user = User.objects.get(email=email)
            # 修改状态
            user.is_staff = True
            # 执行保存操作
            user.save()
    else:
        return HttpResponse('链接有误')

    # 成功后，跳转到登录页面
    return redirect('users:login')


def login_view(request):
    """登录功能"""

    # 如果不是POST请求，这里显示空的表单
    if request.method != 'POST':
        form = LoginFrom()
    else:  # 否则显示表单，并获取表单的数据
        form = LoginFrom(request.POST)
        if form.is_valid():  # 验证表单的数据类型是否正确
            # 验证正确后，开始获取表单中的数据
            username = request.POST['username']
            password = request.POST['password']
            # 进行登录验证
            user = authenticate(request, username=username, password=password)

            if user is not None:
                # 执行登录操作
                login(request, user)

                # 登录成功，跳转到指定页面
                # return HttpResponse('登录成功！')
                # 登录成功后，默认跳转到个人中心
                return redirect('users:user_profile')
            else:
                # 验证不通过
                return HttpResponse('登录失败！')
    # 定义上下文字典
    context = {'form': form}
    return render(request, 'users/login.html', context)


def register(request):
    """注册功能视图"""
    if request.method != 'POST':
        # 如果不是POST请求，先显示注册表单
        form = RegisterForm()
    else:
        # 如果不是空表单，就获取其中的数据
        form = RegisterForm(request.POST)
        # 对表单中的数据进行有效性验证，如果是有效的，就进行保存操作
        if form.is_valid():
            # 先暂存，生成数据对象，此时保存的密码是明文的，需要先转成哈希值，再存到数据库
            new_user = form.save(commit=False)
            # 将明文密码转为哈希值，通过form.cleaned_data.get('password')：获取密码的值
            new_user.set_password(form.cleaned_data.get('password'))
            # 让username等于邮箱即可
            new_user.username = form.cleaned_data.get('email')

            # 将新用户保存到数据库中
            new_user.save()

            # 注册成功后，发送邮件，传入两个参数，一个说新注册的邮箱，一个是发送邮件的类型
            """
            form.cleaned_data.get('email'):获取新注册用户的邮箱
            register：发送验证码的类型
            """

            send_register_email(form.cleaned_data.get('email'), 'register')
            # 成功后，输出提示信息
            return HttpResponse('注册成功')

    # 定义一个上下文
    context = {'form': form}
    return render(request, 'users/register.html', context)


def forget_pwd(request):
    """找回密码"""
    if request.method == 'GET':  # 如果是GET请求，显示空表单
        form = ForgetPwdForm()
    elif request.method == 'POST':
        form = ForgetPwdForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            exists = User.objects.filter(email=email).exists()
            if exists:
                # 发送邮件
                send_register_email(email, 'forget')
                return HttpResponse('邮件已发送，请注意查收！')
            else:
                return HttpResponse('邮箱未注册，请先注册！')

        # 定义一个上下文
    context = {'form': form}
    return render(request, 'users/forget_pwd.html', context)


def forget_pwd_url(request, active_code):
    if request.method != 'POST':  # 显示空表单
        form = ModifyPwdForm()
    else:
        form = ModifyPwdForm(request.POST)
        if form.is_valid():
            record = EmailVerifyRecord.objects.get(code=active_code)
            email = record.email
            user = User.objects.get(email=email)
            user.username = email
            user.password = make_password(form.cleaned_data.get('password'))
            user.save()
            return HttpResponse('修改成功')
        else:
            return HttpResponse('修改失败')
        # 定义一个上下文
    context = {'form': form}
    return render(request, 'users/reset_pwd.html', context)


@login_required(login_url='users:login')  # 没有登录，执行跳转；跳转到登录页面
def user_profile(request):
    """个人中心视图"""
    # request.user，获取当前登录的用户
    user = User.objects.get(username=request.user)
    # 上下文信息
    context = {'user': user}

    return render(request, 'users/user_profile.html', context)
